﻿namespace HuwmanCode.ServiceProcess

open System
open System.ServiceProcess
open System.Runtime.InteropServices

[<AutoOpen>]
module ServiceControllerExtension =
    let private getServiceConfig(scHandle:SafeHandle) =
        let handle = scHandle.DangerousGetHandle()
        let infoPtr = Marshal.AllocHGlobal(4096)
        try
            let mutable bytesNeeded = 0
            if (QueryServiceConfig(handle, infoPtr, 4096, &bytesNeeded)) then
                Marshal.PtrToStructure(infoPtr, typeof<ServiceConfigInfo>) :?> ServiceConfigInfo
            else failwith "Unable to query service config!"
        finally 
            Marshal.FreeHGlobal(infoPtr)

    type System.ServiceProcess.ServiceController with
        ///<summary>
        /// The executable path for the windows service
        ///</summary>
        member sc.ExecutablePath
            with public get() = 
                let info = sc.ServiceHandle |> getServiceConfig
                info.BinaryPathName